package com.inepex.graphicstests.client.govscanvasperf;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.inepex.graphicstests.client.misc.Globals;
import com.inepex.graphicstests.client.misc.GraphicalObjectFactory;
import com.inepex.inegraphics.impl.client.DrawingAreaGWT;
import com.inepex.inegraphics.impl.client.IncrementalUpdaterImpl;
import com.inepex.inegraphics.shared.GraphicalObjectContainer;
import com.inepex.inegraphics.shared.gobjects.GraphicalObject;

public class GraphicsIntelligentUsage extends Composite implements Runnable{
	private FlowPanel mainPanel;
	private DrawingAreaGWT drawingArea;
	
	private GraphicalObjectContainer gos;
	
	public GraphicsIntelligentUsage() {
		gos = new GraphicalObjectContainer();
		init();
		fillUpGOC();
	}
	
	private void init(){
		mainPanel = new FlowPanel();
		drawingArea = new DrawingAreaGWT(Globals.width, Globals.height);
		
		mainPanel.add(drawingArea.getWidget());
		
		initWidget(mainPanel);	

		DOM.setStyleAttribute(drawingArea.getWidget().getElement(), "border", "1px solid black");
	}
	
	private void start(){
		Main.getRunner().run(this);
	}

	
	@Override
	protected void onLoad() {
		start();
//		doPartialUpdate();
		super.onLoad();
	}

	@Override
	public int doUpdate() {
		drawingArea.removeAllGraphicalObjects();
		changePosAndContexts();
		drawingArea.add(gos);
		drawingArea.update();
		return drawingArea.getGraphicalObjects().size();
//		return doPartialUpdate();
	}
	
	final Image loading = new Image(Globals.getRes().loading());
	
	public int doPartialUpdate(){
		mainPanel.add(loading);
		
		changePosAndContexts();
		drawingArea.add(gos);
		new IncrementalUpdaterImpl(drawingArea) {

			@Override
			public void onFinished() {
				mainPanel.remove(loading);
			}
			
		};
		
		return drawingArea.getGraphicalObjects().size();
	}
	
	private void fillUpGOC(){
		gos.removeAllGraphicalObjects();
		for(int i=0; i<Globals.goCount; i++){
			GraphicalObject go = GraphicalObjectFactory.getRandomGraphicalObjectWithNullContext();
			GraphicalObjectFactory.setRandomPosition(go);
			go.setContext(GraphicalObjectFactory.getRandomContext_WithoutShadows());
			gos.add(go);
		}
	}
	
	private void changePosAndContexts(){
		for(GraphicalObject go : gos.getGraphicalObjects()){
			GraphicalObjectFactory.setRandomPosition(go);
			go.setContext(GraphicalObjectFactory.getRandomContext_WithoutShadows());
		}
	}
}